package com.zlt.appparking.tast;

import com.zlt.appparking.entity.AppUser;
import com.zlt.appparking.entity.AppUserExample;
import com.zlt.appparking.entity.Appointment;
import com.zlt.appparking.entity.AppointmentExample;
import com.zlt.appparking.mapper.AppUserMapper;
import com.zlt.appparking.mapper.AppointmentMapper;
import com.zlt.appparking.utils.CodeUtil.CodeUtil;
import com.zlt.appparking.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 定时任务
 * 查所有的预约单，
 */
@Component
public class SchedulingTask {

    @Autowired
    private AppointmentMapper appointmentMapper;

    @Autowired
    private AppUserMapper appUserMapper;

    @Scheduled(cron = "0 0/1 * * * ? ")
    public void SchedulingAppointment() throws ParseException {

        AppointmentExample appointmentExample = new AppointmentExample();
        appointmentExample.createCriteria().andApStateEqualTo((byte) 0);
        List<Appointment> appointments = appointmentMapper.selectByExample(appointmentExample);


        for (Appointment appointment : appointments) {
            System.out.println("appointment" + appointment.toString());

            //当前时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = StringUtil.getCurrentTime();
            Date date = simpleDateFormat.parse(currentTime);

            //预定时间
            Date apStart = appointment.getApStart();

            //2、时间戳相减
            long time = apStart.getTime(); //预定时间的时间戳

            long nowDateTime = date.getTime();//当前时间戳

            int result = (int) (nowDateTime - time);//毫秒

            int diffMinute = result / 1000 / 60;//60秒等于1分钟

            System.out.println(diffMinute);
            //等于10  快要过期了 然后发送消息
            if (diffMinute == 0) {
                AppUserExample appUserExample = new AppUserExample();
                appUserExample.createCriteria().andAuIdEqualTo(appointment.getAuId());

                List<AppUser> appUsers = appUserMapper.selectByExample(appUserExample);
                System.out.println("应该发送的对象手机号：" + appUsers.get(0).getAuPhone());
                CodeUtil.sendExpire(appUsers.get(0).getAuPhone());
            }
            //大于10  通过0状态码还能查到你 意味着你违约了  预订单过期 状态码为2
            if (diffMinute > 10) {
                appointment.setApState((byte) 2);
                appointmentMapper.updateByPrimaryKeySelective(appointment);
            }

        }
    }

}
